import BaseMapHandler from './BaseMapHandler';

export default class PolygonDrawHandler extends BaseMapHandler {
  name = '绘制多边形'
  type = 'polygon-draw'
  description = '绘制无交叉多边形'
  active = false
  private points: Array<{ lat: number, lng: number }> = []
  private markers: any[] = []
  private polyline: any = null
  private polygon: any = null
  private clickListener: any = null
  private rightClickListener: any = null

  constructor(private onPolygonComplete: (points: Array<{ lat: number, lng: number }>) => void) {
    super()
  }

  activate(): void {
    this.active = true
    this.setupEventListeners()
    console.log('多边形绘制已激活')
  }

  deactivate(): void {
    this.active = false
    this.cleanup()
    console.log('多边形绘制已停用')
  }

  handle(): void {
    // 处理器激活时开始绘制模式
    console.log('多边形绘制模式已启动')
  }

  private setupEventListeners(): void {
    if (!this.active) {
      console.log('PolygonDrawHandler: 未激活，跳过事件设置')
      return
    }

    const map = (window as any).mapController.getMap()
    if (!map) {
      console.warn('PolygonDrawHandler: 地图实例为null')
      return
    }

    const qq = (window as any).qq


    try {
      // 直接绑定click事件到地图实例
      this.clickListener = qq.maps.event.addListener(map, 'click', (event: any) => {
        const lat = event.latLng.lat
        const lng = event.latLng.lng
        this.handleMapClick({ latLng: { lat, lng } })
      })

      this.rightClickListener = qq.maps.event.addListener(map, 'rightclick', (_event: any) => {
        this.completePolygon()
      })


    } catch (error) {
      console.error('PolygonDrawHandler: 设置事件监听器失败', error)
    }
  }

  private handleMapClick(event: any): void {
    if (!this.active) return

    const lat = event.latLng.lat
    const lng = event.latLng.lng
    const point = { lat, lng }

    if (!this.canAddPoint(point)) {
      console.log('无法添加点：会导致线段交叉')
      return
    }

    this.addPoint(point)
  }

  private canAddPoint(newPoint: { lat: number, lng: number }): boolean {
    if (this.points.length < 2) return true

    const testPoints = [...this.points, newPoint]

    // 检查线段交叉
    if (this.hasCrossingSegments(testPoints)) {
      return false
    }

    // 检查闭合线段是否会交叉
    if (testPoints.length >= 3 && this.hasClosingCrossing(testPoints)) {
      return false
    }

    return true
  }

  private addPoint(point: { lat: number, lng: number }): void {
    this.points.push(point)
    this.addMarker(point)
    this.updatePolyline()

    console.log(`已添加点 ${this.points.length}: ${point.lat}, ${point.lng}`)

    if (this.points.length === 3) {
      console.log('已选择3个点，右键点击地图任意位置完成多边形')
    } else if (this.points.length > 3) {
      console.log(`已选择${this.points.length}个点，右键点击地图任意位置完成多边形`)
    }
  }

  private addMarker(point: { lat: number, lng: number }): void {
    const map = (window as any).mapController.getMap()
    if (!map) return

    const marker = this.createMarker(map, point, `点 ${this.markers.length}`)
    this.markers.push(marker)
  }

  private updatePolyline(): void {
    const map = (window as any).mapController.getMap()
    if (!map) return

    if (this.polyline) {
      this.polyline.setMap(null)
    }

    if (this.points.length > 1) {
      this.polyline = this.createPolyline(map, this.points)
    }
  }



  private completePolygon(): void {
    if (this.points.length < 3) {
      console.log('需要至少3个点才能形成多边形')
      return
    }

    if (this.hasCrossingSegments(this.points)) {
      console.log('多边形无效：存在线段交叉')
      return
    }

    this.drawPolygon()
    console.log('多边形绘制完成！顶点坐标：', this.points)

    // 触发多边形编辑事件
    this.onPolygonComplete(this.points)

    this.cleanup()
  }

  private drawPolygon(): void {
    const map = (window as any).mapController.getMap()
    if (!map || this.points.length < 3) return

    if (this.polyline) {
      this.polyline.setMap(null)
    }

    this.polygon = this.createPolygon(map, this.points)

  }

  private hasCrossingSegments(points: Array<{ lat: number, lng: number }>): boolean {
    if (points.length < 3) return false

    // 检查所有非相邻线段是否交叉as
    for (let i = 0; i < points.length - 2; i++) {
      for (let j = i + 2; j < points.length - 1; j++) {
        if (this.doSegmentsIntersect(points[i], points[i + 1], points[j], points[j + 1])) {
          return true
        }
      }
    }

    return false
  }

  private hasClosingCrossing(points: Array<{ lat: number, lng: number }>): boolean {
    if (points.length < 3) return false

    const lastPoint = points[points.length - 1]
    const firstPoint = points[0]

    // 只检查闭合线段与非相邻的中间线段是否交叉
    // 跳过相邻的线段（点1->点2和点n-1->点n）
    for (let i = 1; i < points.length - 2; i++) {
      if (this.doSegmentsIntersect(lastPoint, firstPoint, points[i], points[i + 1])) {
        return true
      }
    }

    return false
  }

  private doSegmentsIntersect(p1: { lat: number, lng: number }, p2: { lat: number, lng: number },
    p3: { lat: number, lng: number }, p4: { lat: number, lng: number }): boolean {
    const det = (a: number, b: number, c: number, d: number) => a * d - b * c
    const x1 = p1.lng, y1 = p1.lat
    const x2 = p2.lng, y2 = p2.lat
    const x3 = p3.lng, y3 = p3.lat
    const x4 = p4.lng, y4 = p4.lat

    const denom = det(x1 - x2, y1 - y2, x3 - x4, y3 - y4)
    if (Math.abs(denom) < 1e-10) return false

    const t = det(x1 - x3, y1 - y3, x3 - x4, y3 - y4) / denom
    const u = det(x1 - x2, y1 - y2, x1 - x3, y1 - y3) / denom

    return t >= 0 && t <= 1 && u >= 0 && u <= 1
  }

  private cleanup(): void {

    if (this.clickListener) {
      const qq = (window as any).qq
      qq.maps.event.removeListener(this.clickListener)
      this.clickListener = null

    }

    if (this.rightClickListener) {
      const qq = (window as any).qq
      qq.maps.event.removeListener(this.rightClickListener)
      this.rightClickListener = null

    }

    this.markers.forEach(marker => marker.setMap(null))
    this.markers = []

    if (this.polyline) {
      this.polyline.setMap(null)
      this.polyline = null
    }

    if (this.polygon) {
      this.polygon.setMap(null)
      this.polygon = null
    }

    this.points = []

  }
}